import {
  clearChatContext,
  clearNewChat,
  selectChatHistoryItem,
  setChatHistory,
  setNewChat,
} from "@/utils/chat";
import { dataAnalysis, knowledgeBase } from "@/utils/common";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { remove } from "lodash";
import { useUpdateEffect } from "ahooks";
import { useTranslation } from "react-i18next";
import {
  fetchDelSession,
  fetchSessions,
  fetchUpdateSession,
} from "@/pages/BigScreen/context/services";
import { useGlobalData } from "@/pages/BigScreen/context/chat";
import { ChatContext } from "@/pages/BigScreen/context/store";
import { message } from "antd";
import { ChatTabContext } from "@/pages/BigScreen/context/chatTab";
import store from "store2";

function useChatHistory() {
  const { setChatScene, chatInputFooterRef } = useGlobalData();
  const { changeSession } = useContext(ChatContext);
  const { changeTab } = useContext(ChatTabContext);
  const [isLoading, setIsLoading] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState<any>({});
  const { t } = useTranslation();
  const talkListsRef = useRef<any>([]);

  // 对话历史
  const [talkLists, setTalkLists] = useState<any>([]);
  // 对话历史用于筛选展示的列表
  // const [talkFilterLists, setTalkFilterLists] = useState<any>([]);
  // 当前对话上下文
  const [selectTalk, setSelectTalk] = useState<{
    id?: string;
    content?: string;
  }>({});
  const [searchGroup, setSearchGroup] = useState<string>("");

  const talkFilterLists = useMemo(() => {
    return talkLists.filter((item) => item?.content?.includes(searchGroup));
  }, [talkLists, searchGroup]);

  const delSession = async (id, cb?: any) => {
    setIsLoading(true);
    const res = await fetchDelSession(id);
    setIsLoading(false);

    const { success, msg } = res;
    if (success) {
      let cList = [...talkLists];
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      remove(cList, function (n) {
        return n.id === id;
      }) ?? [];
      // 删除后默认选中 通用对话
      let newList = cList.filter((item) => item.type === "text_chat");
      let cSessionItem = newList?.[0] ?? {};
      if (cSessionItem?.id) {
        setSelectTalk(cSessionItem);
        selectChatHistoryItem(cSessionItem);
        changeSession(cSessionItem);
      } else {
        clearChatContext();
        setNewChat();
        setSelectTalk({});
        selectChatHistoryItem({} as any);
      }
      console.log("delSession cSessionItem", cSessionItem);
      setChatScene("default");
      onRefreshSession();

      cb?.();
    } else {
      return message.error(msg);
    }
  };

  const onHandleChangeTalk = (type, selectTalk, cb?: any) => {
    console.log("onHandleChangeTalk selectTalk", selectTalk);
    if (type === "add") {
      newChat();
    } else if (type === "select") {
      if (
        selectTalk.type.includes(knowledgeBase) ||
        selectTalk.type === dataAnalysis
        // || selectTalk.type === chatTPT
      ) {
        // 知识库/数据集: 需要同步修改  chatScene
        setChatScene(selectTalk.type);
      } else {
        // 普通
        setChatScene("default");
      }
      chatInputFooterRef?.current?.handleChatOlIndex("");
      setSelectTalk(selectTalk);
      selectChatHistoryItem(selectTalk);

      //
      if (cb) {
        cb();
      } else {
        //  没有传入回调直接跳转首页
        setTimeout(() => {
          changeTab("0");
        }, 200);
      }
    } else if (type === "del") {
      delSession(selectTalk.id);
    }
  };

  /**
   * @description: 更新会话标题
   * @param {any} task 会话
   * @return {*}
   */
  const updateTask = (task: any) => {
    // ! 直接走刷新逻辑,不在自己维护
    onRefreshSession();
  };

  const updateSession = async () => {
    const dto = {
      id: currentTask.id,
      summary: currentTask.content || "新会话",
    };
    const { success, msg } = await fetchUpdateSession(dto);
    if (success) {
      const updateItem = {
        id: dto.id,
        content: dto.summary,
      };
      updateTask(updateItem);
      setDialogVisible(false);
    } else {
      return message.error(msg);
    }
  };

  const editTask = (item) => {
    setCurrentTask(item);
    setDialogVisible(true);
  };

  const newChat = () => {
    // 通过注入 isNewChat 到 local, 页面返回 后修改为false
    setIsLoading(true);
    setChatScene("default");
    clearChatContext();
    setNewChat();
    setTimeout(() => {
      setIsLoading(false);
      changeTab("0");
    }, 500);
  };

  const onRefreshSession = async () => {
    setIsLoading(true);
    const res = await fetchSessions();
    setIsLoading(false);
    const { success, msg, content = {} } = res;
    if (success) {
      const { list = [] } = content as any;
      // 获取到的内容需要过滤, 目前只支持 text_chat: 因为只有通用对话场景
      // .filter(item => item.summary)
      let filterSessions = list
        .filter((item) => item?.type === "text_chat")
        .map((item) => {
          return {
            ...item,
            content: item.summary || "新会话",
          };
        });

      setTalkLists(filterSessions);
      setSearchGroup("");

      // 设置会话列表
      setChatHistory(filterSessions);
      // 设置当前会话
      let currentTalk = store.get("supcon.bs.chatContext");
      let targetTalkIndex = filterSessions.findIndex(
        (item) => item.id === currentTalk?.id
      );

      if (targetTalkIndex === -1) {
        // 当前会话不在列表中, 说明是新的会话, 更新当前会话
        selectChatHistoryItem({} as any);
        setSelectTalk({});
      } else {
        // ! 查询出的历史和默认新构造的会话名称不一致,这边更新一下
        // let talkTitle = currentTalk.summary || currentTalk.content;
        // if (targetTalk.summary !== talkTitle) {
        //   selectChatHistoryItem(targetTalk);
        //   setSelectTalk(targetTalk);
        // }
        // 直接替换
        let targetTalk = filterSessions?.[targetTalkIndex] ?? {};
        selectChatHistoryItem(targetTalk);
        setSelectTalk(targetTalk);
      }
    }
  };

  useEffect(() => {
    if (selectTalk.id) {
      clearNewChat();
    }
  }, [selectTalk]);

  useUpdateEffect(() => {
    if (!dialogVisible) {
      let cTalk = store.get("supcon.bs.chatContext") || {};
      let cTalkLists = store.get("supcon.bs.chatHistory") || [];
      talkListsRef.current = cTalkLists;
      setSelectTalk(cTalk);
      setTalkLists([...cTalkLists]);
      setSearchGroup("");
    }
  }, [dialogVisible]);

  useEffect(() => {
    onRefreshSession();
  }, []);

  useEffect(() => {
    setIsLoading(false);
  }, []);

  return {
    talkLists,
    selectTalk,
    dialogVisible,
    currentTask,
    isLoading,
    talkListsRef,
    talkFilterLists,
    searchGroup,

    newChat,
    onHandleChangeTalk,
    updateTask,
    updateSession,
    setDialogVisible,
    editTask,
    setCurrentTask,
    onRefreshSession,
    setSearchGroup,
  };
}

export default useChatHistory;
